package com.rocketmq.controller.consumer;

import com.rocketmq.api.IOrderService;
import com.rocketmq.bean.OrderBean;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单系统消费者
 */
@Controller
@RequestMapping("/order")
public class OrderSystemConsumer {

    @Autowired
    private IOrderService orderService;

    @RequestMapping("/consume")
    @ResponseBody
    public String consumeOrder() throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("OrderSystemConsumer");
        // 填入元数据连接地址
        consumer.setNamesrvAddr("100.85.217.111:8200;100.93.3.194:8200");

        consumer.subscribe("OrderTopic", "*");

        consumer.registerMessageListener(new MessageListenerOrderly() {
            AtomicLong consumeTimes = new AtomicLong(0);

            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                for (MessageExt ext : msgs) {
                    // 获取定时订单消息
                    if ("ScheduledOrderTag".equals(ext.getTags())) {
                        // 订单超时未支付则关闭订单
                        OrderBean orderBean = new OrderBean(false);
                        if (orderBean.isPay()) {
                            orderBean.setStatus("closed");
                            orderService.updateOrder(orderBean);
                        }
                    }
                }

                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                this.consumeTimes.incrementAndGet();
                if ((this.consumeTimes.get() % 3) == 0) {
                    context.setSuspendCurrentQueueTimeMillis(3000);
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }

                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();
        return "consuming order...";
    }

}
